using BuildingBlocks.Application.Messaging;
using BuildingBlocks.Domain;
using Catalog.Api.Data;
using Catalog.Api.Models;

namespace Catalog.Api.Features.CatalogItems.Create;  
  
public sealed class CreateCatalogItemCommandHandler(  
    CatalogDbContext context,  
    ILogger<CreateCatalogItemCommandHandler> logger)  
    : ICommandHandler<CreateCatalogItemCommand, string>  
{  
    public async ValueTask<Result<string>> Handle(  
        CreateCatalogItemCommand request,  
        CancellationToken cancellationToken)  
    {  
        var item = new CatalogItem  
        {  
            Name = request.Name,  
            Description = request.Description,  
            Price = request.Price,  
            Stock = request.Stock,  
            PictureUrl = request.PictureUrl,  
            Category = request.Category,  
            CreatedAt = DateTime.UtcNow  
        };  
  
        await context.CatalogItems.InsertOneAsync(item, cancellationToken: cancellationToken);  
  
        logger.LogInformation("Catalog item {ItemName} created with id {ItemId}", item.Name, item.Id);  
  
        return Result.Success(item.Id);  
    }  
}
